 //init
 var OBJDATA = [];
 var taille_w = $('#lin').width();
 var taille_h = $('#lin').height();
 var offset = $('#lin').offset();
var width_viewbox = taille_w;
var height_viewbox = taille_h;
var ratio_viewbox = height_viewbox / width_viewbox;
var originX_viewbox = 0;
var originY_viewbox = 0;
var zoom = 1;
var factor = 1;
var pox = 0;
var poy = 0;
var drag = 'off';
var grid_snap = 'off';
var cur_data={};
 
 
 $('svg').each(function() {
    $(this)[0].setAttribute('viewBox', originX_viewbox + ' ' + originY_viewbox + ' ' + width_viewbox + ' ' + height_viewbox)
});



function throttle(callback, delay) {
    var last;
    var timer;
    return function () {
        var context = this;
        var now = +new Date();
        var args = arguments;
        if (last && now < last + delay) {
            // le délai n'est pas écoulé on reset le timer
            clearTimeout(timer);
            timer = setTimeout(function () {
                last = now;
                callback.apply(context, args);
            }, delay);
        } else {
            last = now;
            callback.apply(context, args);
        }
    };
}

function cursor(tool) {
  if (tool == 'grab') tool = "url('https://wiki.openmrs.org/s/en_GB/7502/b9217199c27dd617c8d51f6186067d7767c5001b/_/images/icons/emoticons/add.png') 8 8, auto";
  if (tool == 'scissor') tool = "url('https://maxcdn.icons8.com/windows10/PNG/64/Hands/hand_scissors-64.png'), auto";
  if (tool == 'trash') tool = "url('https://cdn4.iconfinder.com/data/icons/common-toolbar/36/Cancel-32.png'), auto";
  if (tool == 'validation') tool = "url('https://images.fatguymedia.com/wp-content/uploads/2015/09/check.png'), auto";
  $('#lin').css('cursor',tool);
}

tactile = false;
function calcul_snap(event, state) {
  if (event.touches) {
    var touches = event.changedTouches;
    console.log("toto")
    eX = touches[0].pageX;
    eY = touches[0].pageY;
    tactile = true;
  }
  else {
    eX = event.pageX;
    eY = event.pageY;
  }
    x_mouse = (eX * factor) - (offset.left * factor) + originX_viewbox;
    y_mouse = (eY * factor) - (offset.top * factor) + originY_viewbox;

    if (state == 'on') {
        x_grid = Math.round(x_mouse / grid) * grid;
        y_grid = Math.round(y_mouse / grid) * grid;
    }
    if (state == 'off') {
        x_grid = x_mouse;
        y_grid = y_mouse;
    }
    return {
        x: x_grid,
        y: y_grid,
        xMouse: x_mouse,
        yMouse: y_mouse
    };
}
function _MOUSEUP(event) {
   
  if($("#movingDom")[0])
	 {
		 
	 }
	 else
	 {
		 
		     drag = 'off';
		moveingObject=null;
		cursor('default');
		checkDragEnd(event);
	 }

}

function _MOUSEDOWN(event) {

     if(event.preventDefault)
     event.preventDefault();
     drag = 'on';
	 snap = calcul_snap(event, grid_snap);
     pox = snap.xMouse;
     poy = snap.yMouse;
	 if($("#movingDom")[0])
	 {
		 let dom=$("#movingDom");
		 let objectType=dom.attr("objectType");
		  
			if((objectType=="circle_addNode"||objectType=="circle_addCuttingNode")&&editor_json.cx)
			{
				let cur_node=cur_data["vertexs"][editor_json.index];
				let nextnode=cur_node.nextnode;
				let equation=qSVG.createEquation(cur_node,nextnode);
				let x=editor_json.cx,y=editor_json.cy;
				if(equation.A=="h") 
				{
					y=equation.B;
				}
				else if(equation.A=="v") 
				{
					x=cur_node.x;
				}
				else 
				{
					y=equation.A*editor_json.cx+equation.B;
				}
				let json={x,y};
				if(objectType=="circle_addCuttingNode")
				{
					if(cur_data.cuttingpointCount==null)
					{
						cur_data.cuttingpointCount=0;
					}
					else
					{
						
						cur_data.cuttingpointCount++;
					}
					
					json.cuttingIndex=cur_data.cuttingpointCount;
				}
				cur_data["vertexs"].splice(editor_json.index+1,0,json);
				load(cur_data);
				editor_json={};
				// $('.btn-success').removeClass('btn-success');
				// $("#movingDom").remove();
			}
	 }
     

}
function _MOUSEMOVE(event) {
	 
	
	
    checkDragEnd(event);
	event.preventDefault(); 
   
     
	
}
var addLock=false;
function checkDragEnd(event)
{
	
	 if ( drag == 'on') {
		 
		
		 if(moveingObject!=null)
		{
			
			snap = calcul_snap(event, grid_snap);
			 
			let distX = (snap.x) ;
	        let distY = (snap.y);
			let objectType=moveingObject.attr("objectType");
		 
			switch(objectType)
			{ 
			    case "circle_deleteNode" :
				case "circle_addNode":
				case "circle_addCuttingNode":
				case "circle_deleteCuttingNode":
				{   
				    
					moveingObject.attr('cx', distX);
			        moveingObject.attr('cy', distY);
					 
					break;
				}
				case "circle_hhl":
				{   
				    let index=moveingObject.attr("index")*1;
	                let cur_node=cur_data["vertexs"][index];
					cur_node.x=distX;
					cur_node.y=distY;
					
					moveingObject.attr('cx', distX);
			        moveingObject.attr('cy', distY);
					moveingObject.attr("fill-opacity",1);
					 
					load(cur_data);
					break;
				}
				 case "line_hhl":
				{   
				    let index=moveingObject.attr("index")*1;
	                let cur_node=cur_data["vertexs"][index];
				    let nextnode=cur_node.nextnode;
				    let equation=qSVG.createEquation(cur_node,nextnode);
					let equation_pre=qSVG.createEquation(cur_node.prenode,cur_node);
					let equation_next=qSVG.createEquation(nextnode,nextnode.nextnode);
				    let x,y;
					let order=0;
					if((equation.A==equation_pre.A)&&(equation.B==equation_pre.B))
					{
						//左共线，增加左顶点
						cur_data["vertexs"].splice(index,0,{x:cur_node.x,y:cur_node.y});
						moveingObject.attr("index",index+1);
						order=1;
						 
					}
					if((equation.A==equation_next.A)&&(equation.B==equation_next.B))
					{
						//右共线，增加右顶点
						cur_data["vertexs"].splice(index+order+2,0,{x:nextnode.x,y:nextnode.y});
					 
					}
				    if(equation.A=="h") 
				    {
					  y=distY;
					  cur_node.y=distY;
					  nextnode.y=distY;
				    }
				    else if(equation.A=="v") 
				    {
					  x=distX;
					  cur_node.x=distX;
					  nextnode.x=distX;
				    }
				    load(cur_data);
				   /*
					cur_node.x=distX;
					cur_node.y=distY;
					
					moveingObject.attr('cx', distX);
			        moveingObject.attr('cy', distY);
					moveingObject.attr("fill-opacity",1);
					 
					load(cur_data);
					*/
					break;
				}
				case "ellipse":
				{  moveingObject.attr('cx', distX);
			       moveingObject.attr('cy', distY);
					break;
				}
				case "rectangle":
				{  moveingObject.attr('x', distX);
			       moveingObject.attr('y', distY);
					break;
				}
			}
			
		}
	    else
		 { 
	       
		 
			snap = calcul_snap(event, grid_snap);
			let distX = (snap.xMouse - pox) * factor;
	        let distY = (snap.yMouse - poy) * factor;
			$('#lin').css('cursor', 'move');
			zoom_maker('zoomdrag', distX, distY);
			 
		 }
       
    }
	
}
function zoom_maker(lens, xmove, xview) {
  
    if (lens == 'zoomout' && zoom > 1 && zoom < 14) {
      
        width_viewbox += xmove;
		zoom--;
        var ratioWidthZoom =  taille_w / width_viewbox;
        height_viewbox = width_viewbox * ratio_viewbox;
        myDiv = document.getElementById("scaleVal");
        myDiv.style.width =  fix_rule*ratioWidthZoom+'px';
        originX_viewbox = originX_viewbox - (xmove/2);
        originY_viewbox = originY_viewbox - (xmove/2 * ratio_viewbox);
    }
    if (lens == 'zoomin' && zoom < 14 && zoom > 0) {
     
        var oldWidth = width_viewbox;
		if(width_viewbox -xmove<0) return;
        width_viewbox -= xmove;
		
		   zoom++;
        var ratioWidthZoom = taille_w / width_viewbox;
        height_viewbox = width_viewbox * ratio_viewbox;
        myDiv = document.getElementById("scaleVal");
        myDiv.style.width = fix_rule*ratioWidthZoom+'px';

        originX_viewbox =  originX_viewbox + (xmove/2);
        originY_viewbox =  originY_viewbox + (xmove/2 * ratio_viewbox);
    }
    factor = width_viewbox / taille_w;
    if (lens == 'zoomreset') {
      originX_viewbox = 0;
      originY_viewbox = 0;
      width_viewbox = taille_w;
      height_viewbox = taille_h;
      factor = 1;
    }
    if (lens == 'zoomright') {
        originX_viewbox += xview;
    }
    if (lens == 'zoomleft') {
        originX_viewbox -= xview;
    }
    if (lens == 'zoomtop') {
        originY_viewbox -= xview;
    }
    if (lens == 'zoombottom') {
        originY_viewbox += xview;
    }
    if (lens == 'zoomdrag') {
        originX_viewbox -= xmove;
        originY_viewbox -= xview;
    }
	
    $('svg').each(function() {
        $(this)[0].setAttribute('viewBox', originX_viewbox + ' ' + originY_viewbox + ' ' + width_viewbox + ' ' + height_viewbox)
    });
}
var order_id=(getQueryVariable("order_id"));
var goods_id=(getQueryVariable("goods_id"));
function export_plan()
{
	// $('#lin').children(".hhl").empty();
	 let block_index=0;
  	 let vertexs=cur_data.vertexs;
	 let vertexs1=[];
	 let stack_index=0;
	 let d_stack=[[]];
     let cutting_stack=[];
	 for(let i=0;i<vertexs.length;i++)
	 {
		 
		 let cur_node=vertexs[i];
		 vertexs1.push({
			 x:cur_node.x,
			 y:cur_node.y,
			 cuttingIndex:cur_node.cuttingIndex
		 });
		 let nextnode=cur_node.nextnode,prenode=cur_node.prenode;
		  let enter_cutting_stack=false;
		   d_stack[stack_index].push(cur_node);
		  if(cur_node.cuttingIndex!=null) 
	      {
			   
				if(cutting_stack.length==0)
                {
					enter_cutting_stack=true;
				}
                else
				{ 
			        if(Math.floor(cutting_stack[cutting_stack.length-1].cuttingIndex/2)==Math.floor(cur_node.cuttingIndex/2))
			        {
						let node=cutting_stack.pop();
 						stack_index--;
						d_stack[stack_index].push(cur_node);
						
					}
					else
					{
						enter_cutting_stack=true;
						
					}
					
				}
    				
		  }
		  if(enter_cutting_stack)
		  {
			  cutting_stack.push(cur_node);
			  stack_index++;
			  d_stack.push([cur_node]);
		  }
		
		 
	 }
	 let str=``;
	 let maxx=0;let maxy=0;
	  let minx=0;let miny=0;
	 for(let i=0;i<d_stack.length;i++)
	 {
		 
		 let ary=d_stack[i];
		 let d="";
		 for(let j=0;j<ary.length;j++)
		 {
			 let cur_node=ary[j];
 		     let nextnode=cur_node.nextnode,prenode=cur_node.prenode;
		        let x0=fix_danwei*cur_node.x;
				let y0=fix_danwei*cur_node.y;
				maxx=maxx<x0?x0:maxx;
				maxy=maxy<y0?y0:maxy;
				minx=minx>x0?x0:minx;
				miny=miny>y0?y0:miny;
				 if(j==0)
				 {
					 d+="M "+x0+" "+y0;
					 
					 
				 }
				 else
				 {
					 d+=" L "+x0+" "+y0;
				 }
				 
				 
			
		 }
		 d+=" Z";
		 block_index++;
		 str+=`<path d="${d}" stroke="#666" stroke-width="3" fill="#ffffff" id="${order_id}_${goods_id}_${block_index}" parent_id="0"></path>
		 `;
		 
	 }
	 str=`<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" 
"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg viewbox="${(maxx+minx)/-2}  ${(maxx+minx)/-2}  ${(maxx-minx)*2} ${(maxy-miny)*2} " width="100%" height="100%" version="1.1"
xmlns="http://www.w3.org/2000/svg">
`+str;
	 str+="</svg>"
	 console.log(str);
	 cur_data.vertexs= vertexs1;
	 let str1=JSON.stringify(cur_data);
	 cur_data.vertexs= vertexs;
	 vertexs1=null;
	 let postdata={    
					"action":   "set_goods_setting",
					    "param":  {        
						goods_id:goods_id*1,
					   "struct":str1 ,
						"svg":   str
					}
				} 
	 console.log(postdata);
	 $.post("http://192.168.0.241:5051",JSON.stringify(postdata),function(data,status,xhr){
 
		  if(status!="success")
		  {
  			  return;
		  }
		  alert("保存成功");
	  },"json");
	   
}
function getQueryVariable(variable)
{
       var query = window.location.search.substring(1);
       var vars = query.split("&");
       for (var i=0;i<vars.length;i++) {
               var pair = vars[i].split("=");
               if(pair[0] == variable){return pair[1];}
       }
       return(false);
} 

